package com.jinzhi.jzapi.training.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.service.DictService;
import com.jinzhi.common.utils.ApiResult;
import com.jinzhi.jzapi.training.pojo.ChaItemBankVo;
import com.jinzhi.jzapi.training.pojo.TrainingPaperVo;
import com.jinzhi.jzapi.utils.CerSynthesisUtil;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.service.*;
import com.jinzhi.jzweb.utils.IdCardUtil;
import com.jinzhi.jzweb.utils.ValuesUtil;
import com.jinzhi.jzweb.utils.WithZoreUtil;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.service.UserService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.*;

import static com.jinzhi.api.util.TokenTag.TOKEN_TAG;

@Slf4j
@RestController
@RequestMapping("/jzApi/topic")
public class ApiTopicController extends BaseController {

    @Autowired
    private TrainingPapersService trainingPapersService;
    @Autowired
    private TrainingQuestionsService trainingQuestionsService;
    @Autowired
    private TrainingAnswerSheetService trainingAnswerSheetService;
    @Autowired
    private TrainingResultsService trainingResultsService;
    @Autowired
    private CourseLearnsService courseLearnsService;
    @Autowired
    private CoursesService coursesService;
    @Autowired
    private ChapterService chapterService;
    @Autowired
    private ChapterItemBankService chapterItemBankService;
    @Autowired
    private UserService userService;
     @Autowired
    private LearnRecordService learnRecordService;
    @Autowired
    private TrainingCertificatesService trainingCertificatesService;
    @Autowired
    private OrganizationNewsService organizationNewsService;
    @Autowired
    private DictService dictService;

    /**
     * api小程序端-随机获取章节题目接口
     *
     * @Description: 根据章节id随机抽取10道题目返回；参数：验证token,章节id
     * @Param: [token, id,type]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-04-24
     */
    @GetMapping("/selRandChaTest")
    @Log("api小程序端-随机获取章节题目接口")
    @ApiOperation(value = "api小程序端-随机获取章节题目接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> selRandChaTest(@RequestHeader(value = TOKEN_TAG, required = false) String token, String id) {
        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }
        if (StringUtils.isBlank(id)) {
            return ApiResult.lack("");//缺少参数
        }

        List<ChaItemBankVo> chapterItemBankDO = chapterItemBankService.selRandItemList(Long.parseLong(id));
        if (chapterItemBankDO != null && chapterItemBankDO.size() > 0) {
            return ApiResult.success(chapterItemBankDO);
        } else {
            return ApiResult.fail("暂无题目，敬请期待");
        }
    }

    /**
     * api小程序端-培训题题目接口
     *
     * @Description: 根据类型判断试卷类型并随机抽取一套试卷返回；参数：验证token,课程id,试卷类型（0练习，1测试）
     * @Param: [token, id,type]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-04-24
     */
    @GetMapping("/selpractice")
    @Log("api小程序端-培训题题目接口")
    @ApiOperation(value = "api小程序端-培训题题目接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> selpractice(@RequestHeader(value = TOKEN_TAG, required = false) String token, String id, String type) {
        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }
        if (StringUtils.isBlank(id)) {
            return ApiResult.lack("");//缺少参数
        }
        if (StringUtils.isBlank(type)) {
            return ApiResult.lack("");//缺少参数
        }
        //判断是否为数字
        if (!IdCardUtil.isNumeric(type)) {
            return ApiResult.format("");//格式错误
        }

        Map mapre = new HashMap();

        Map map = new HashMap();
        map.put("type", type);
        map.put("coursesId", Long.parseLong(id));
        TrainingPapersDO trainingPapersDO = trainingPapersService.selRandTraPaList(map);
        if (trainingPapersDO != null) {
            mapre.put("id", trainingPapersDO.getId());//试卷id
            mapre.put("name", trainingPapersDO.getName());//试卷名称
            mapre.put("numbers", trainingPapersDO.getNumbers());//试卷编号

            Map map1 = new HashMap();
            map1.put("tpaperId", trainingPapersDO.getId());
            List<TrainingPaperVo> testPaperVos = trainingQuestionsService.selTestPaper(map1);
            mapre.put("questions", testPaperVos);//试卷试题

            return ApiResult.success(mapre);
        } else {
            return ApiResult.fail("暂无试卷，敬请期待");
        }
    }

    /**
     * api小程序端-试卷提交接口
     *
     * @Description: 提交保存试卷信息（练习和测试共用）；参数：验证token，试卷id,答案集合，考试时间,试卷类型（0练习，1测试）
     * @Param: [token, tpaperId, answerList, time,type]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-04-24
     */
    @PostMapping("/addAnswerSheet")
    @Log("api小程序端-试卷提交接口")
    @ApiOperation("api小程序端-试卷提交接口")
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> addAnswerSheet(@RequestHeader(value = TOKEN_TAG, required = false) String token, String tpaperId, String answerList, String time, String type) {
        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }
        if (StringUtils.isBlank(time)) {
            return ApiResult.lack("");//缺少参数
        }
        if (StringUtils.isBlank(tpaperId)) {
            return ApiResult.lack("");//缺少参数
        }
        if (StringUtils.isBlank(answerList)) {
            return ApiResult.lack("");//缺少参数
        }
        if (StringUtils.isBlank(type)) {
            return ApiResult.lack("");//缺少参数
        }
        //判断是否为数字
        if (!IdCardUtil.isNumeric(type)) {
            return ApiResult.format("");//格式错误
        }
        TrainingPapersDO trainingPapersDO = trainingPapersService.selectById(Long.parseLong(tpaperId));
        if (trainingPapersDO != null) {
            boolean bbdd;
            TrainingAnswerSheetDO answerSheetDO;
            //保存答卷信息
            TrainingAnswerSheetDO trainingAnswerSheetDO = trainingAnswerSheetService.findOneByKv("user_id", user.getId(), "tpapers_id", Long.parseLong(tpaperId));
            if (trainingAnswerSheetDO != null) {
                trainingAnswerSheetDO.setState(0);//默认正常
                trainingAnswerSheetDO.setAnswers(answerList);//答卷集合
                bbdd = trainingAnswerSheetService.updateById(trainingAnswerSheetDO);
                answerSheetDO = trainingAnswerSheetDO;
            } else {
                TrainingAnswerSheetDO trainingAnswerSheet = new TrainingAnswerSheetDO();
                trainingAnswerSheet.setState(0);//默认正常
                trainingAnswerSheet.setUserId(user.getId());//用户id
                trainingAnswerSheet.setTpapersId(Long.parseLong(tpaperId));//培训试卷id
                trainingAnswerSheet.setAnswers(answerList);//答卷集合
                bbdd = trainingAnswerSheetService.insert(trainingAnswerSheet);
                answerSheetDO = trainingAnswerSheet;
            }

            List<Long> ids = trainingQuestionsService.selIdList(trainingPapersDO.getId());
            if (ids != null && ids.size() > 0) {
                if (bbdd) {
                    Integer returnScore = 0;//返回分数
                    String[] ssr = answerList.split("\\{\"id\":\"");
                    for (int i = 1; i < ssr.length; i++) {
                        String[] ssc = ssr[i].split("\"}");
                        for (int j = 0; j < ssc.length; j++) {
                            String[] ssa = ssc[j].split("\",\"value\":\"");
                            if (ssa.length > 1) {
                                //只有在试卷试题中的答案试题才会计算分数，为了防止其他答案重复提交；
                                if (ids.indexOf(Long.parseLong(ssa[0])) > -1) {
                                    TrainingQuestionsDO trainingQuestionsDO = trainingQuestionsService.selectById(Long.parseLong(ssa[0]));
                                    if (trainingQuestionsDO.getType() == 0 || trainingQuestionsDO.getType() == 2) {//单选题和判断题，答案唯一，可以不用拆解了
                                        if (trainingQuestionsDO.getRightKey().equals(ssa[1])) {
                                            returnScore = returnScore + trainingQuestionsDO.getScore();
                                        }
                                    } else if (trainingQuestionsDO.getType() == 1) {//多选题因为答案有多个，需要循环判断一下是否包含该答案
                                        String[] ssb = ssa[1].split(";;");
                                        String answer = "";
                                        for (int n = 0; n < ssb.length; n++) {
                                            if (answer == "") {
                                                answer = ssb[n];
                                            } else {
                                                answer = answer + ";;" + ssb[n];
                                            }
                                        }

                                        if (trainingQuestionsDO.getRightKey().equals(answer)) {
                                            returnScore = returnScore + trainingQuestionsDO.getScore();
                                        }
                                    }
                                }
                            }
                        }
                    }

                    //判断是否已经存入成绩
                    TrainingResultsDO trainingResultsDOsa = trainingResultsService
                            .findOneByKv("courses_id", trainingPapersDO.getCoursesId(), "tpapers_id", trainingPapersDO.getId(), "user_id", user.getId());
                    if (trainingResultsDOsa != null) {
                        trainingResultsDOsa.setTotalScore(returnScore);//考试成绩
                        trainingResultsDOsa.setTimes(Long.parseLong(time));//考试时间
                        if (returnScore >= trainingPapersDO.getPassMark()) {
                            trainingResultsDOsa.setState(1);//状态修改为通过
                        }
                        boolean cc = trainingResultsService.updateById(trainingResultsDOsa);
                        if (!cc) {
                            return ApiResult.fail("答卷已保存，但成绩保存错误，请重试或联系管理员！");
                        }
                    } else {
                        TrainingResultsDO trainingResultsDO = new TrainingResultsDO();
                        trainingResultsDO.setName(trainingPapersDO.getName());//考试名称
                        trainingResultsDO.setCoursesId(trainingPapersDO.getCoursesId());//课程id
                        trainingResultsDO.setTpapersId(trainingPapersDO.getId());//试卷id
                        trainingResultsDO.setUserId(user.getId());//用户id
                        trainingResultsDO.setTotalScore(returnScore);//考试成绩
                        if (returnScore >= trainingPapersDO.getPassMark()) {
                            trainingResultsDO.setState(1);//状态为通过
                        } else {
                            trainingResultsDO.setState(0);//状态正常
                        }

                        trainingResultsDO.setTimes(Long.parseLong(time));//考试时间
                        boolean cc = trainingResultsService.insert(trainingResultsDO);
                        if (!cc) {
                            return ApiResult.fail("答卷已保存，但成绩保存错误，请重试或联系管理员！");
                        }
                    }


                    //测试
                    if (type.equals("1")) {
                        CourseLearnsDO courseLearnsDO = courseLearnsService.findOneByKv("courses_id", trainingPapersDO.getCoursesId(), "user_id", user.getId());
                        if (courseLearnsDO != null) {
                            courseLearnsDO.setTestScores(returnScore);//更新测试成绩
                            boolean bbcd = false;
                            CoursesDO coursesDo = coursesService.selectById(trainingPapersDO.getCoursesId());
                            if (coursesDo != null) {
                                if (coursesDo.getAdoptFactor().equals("所有章节通过")) {
                                    List<ChapterDO> chapterDOS = chapterService.findByKv("courses_id", coursesDo.getId());
                                    if (chapterDOS != null && chapterDOS.size() > 0) {
                                        if (chapterDOS.size() <= courseLearnsDO.getCompletionNumber()) {
                                            courseLearnsDO.setState(0);
                                            bbcd = true;
                                        }
                                    } else {
                                        courseLearnsDO.setState(0);
                                        bbcd = true;
                                    }
                                } else if (coursesDo.getAdoptFactor().equals("测试达到合格")) {
                                    if (trainingPapersDO.getPassMark() <= returnScore) {
                                        courseLearnsDO.setState(0);
                                        bbcd = true;
                                    }
                                } else {
                                    boolean ccdd = true;
                                    List<ChapterDO> chapterDOS = chapterService.findByKv("courses_id", coursesDo.getId());
                                    if (chapterDOS != null && chapterDOS.size() > 0) {
                                        if (chapterDOS.size() > courseLearnsDO.getCompletionNumber()) {
                                            ccdd = false;
                                        }
                                    }

                                    if (trainingPapersDO.getPassMark() > returnScore) {
                                        ccdd = false;
                                    }

                                    if (ccdd) {
                                        courseLearnsDO.setState(0);
                                        bbcd = true;
                                    }
                                }
                            }

                            boolean ccu = courseLearnsService.updateById(courseLearnsDO);
                            if (ccu) {
                                if(bbcd){
                                    boolean ccdde = aBoolean(user.getId(),coursesDo.getId(),user.getName(),user.getHeadPortrait(),user.getIdNumber(),user.getOrgName());
                                    if(ccdde){
                                        Map map = new HashMap();
                                        map.put("score", returnScore);
                                        map.put("answerId", answerSheetDO.getId());//答卷id
                                        return ApiResult.success("成功", map);
                                    }else{
                                        return ApiResult.fail("信息返回错误，请稍后重试！");
                                    }
                                }
                                Map map = new HashMap();
                                map.put("score", returnScore);
                                map.put("answerId", answerSheetDO.getId());//答卷id
                                return ApiResult.success("成功", map);
                            } else {
                                return ApiResult.fail("信息返回错误，请稍后重试！");
                            }
                        } else {
                            boolean bbcd = false;
                            CourseLearnsDO courseLearnsDO1 = new CourseLearnsDO();
                            courseLearnsDO1.setCoursesId(trainingPapersDO.getCoursesId());//课程id
                            courseLearnsDO1.setUserId(user.getId());//用户id
                            courseLearnsDO1.setTestScores(returnScore);//考试成绩
                            courseLearnsDO1.setState(1);//默认未通过

                            CoursesDO coursesDo = coursesService.selectById(trainingPapersDO.getCoursesId());
                            if (coursesDo != null) {
                                if (coursesDo.getAdoptFactor().equals("测试达到合格")) {
                                    if (trainingPapersDO.getPassMark() <= returnScore) {
                                        courseLearnsDO1.setState(0);
                                        bbcd = true;
                                    }
                                }
                            }

                            boolean ccu = courseLearnsService.insert(courseLearnsDO1);
                            if (ccu) {
                                if(bbcd){
                                    boolean ccdde = aBoolean(user.getId(),coursesDo.getId(),user.getName(),user.getHeadPortrait(),user.getIdNumber(),user.getOrgName());
                                    if(ccdde){
                                        Map map = new HashMap();
                                        map.put("score", returnScore);
                                        map.put("answerId", answerSheetDO.getId());//答卷id
                                        return ApiResult.success("成功", map);
                                    }else{
                                        return ApiResult.fail("信息返回错误，请稍后重试！");
                                    }
                                }
                                Map map = new HashMap();
                                map.put("score", returnScore);
                                map.put("answerId", answerSheetDO.getId());//答卷id
                                return ApiResult.success("成功", map);
                            } else {
                                return ApiResult.fail("信息返回错误，请稍后重试！");
                            }
                        }
                    } else {
                        //练习试卷
                        CourseLearnsDO courseLearnsDO = courseLearnsService.findOneByKv("courses_id", trainingPapersDO.getCoursesId(), "user_id", user.getId());
                        if (courseLearnsDO != null) {
                            courseLearnsDO.setPracticeScores(returnScore);//更新练习成绩
                            boolean ccu = courseLearnsService.updateById(courseLearnsDO);
                            if (ccu) {
                                Map map = new HashMap();
                                map.put("score", returnScore);
                                map.put("answerId", answerSheetDO.getId());//答卷id
                                return ApiResult.success("成功", map);
                            } else {
                                return ApiResult.fail("信息返回错误，请稍后重试！");
                            }
                        } else {
                            CourseLearnsDO courseLearnsDO1 = new CourseLearnsDO();
                            courseLearnsDO1.setCoursesId(trainingPapersDO.getCoursesId());//课程id
                            courseLearnsDO1.setUserId(user.getId());//用户id
                            courseLearnsDO1.setPracticeScores(returnScore);//练习成绩
                            courseLearnsDO1.setState(1);//默认未通过
                            boolean ccu = courseLearnsService.insert(courseLearnsDO1);
                            if (ccu) {
                                Map map = new HashMap();
                                map.put("score", returnScore);
                                map.put("answerId", answerSheetDO.getId());//答卷id
                                return ApiResult.success("成功", map);
                            } else {
                                return ApiResult.fail("信息返回错误，请稍后重试！");
                            }
                        }
                    }

                } else {
                    return ApiResult.fail("答卷保存错误，请稍后重试！");
                }
            }
        }

        return ApiResult.fail("信息错误，请稍后重试！");
    }


    boolean aBoolean(Long userId,Long coursesId,String userName,String userPhoto,String userIdCard,String workUnit){
        String url = userPhoto.replace(ValuesUtil.returnUrl, ValuesUtil.localUrl);
        CoursesDO coursesDO = coursesService.selectById(coursesId);
        if (coursesDO != null) {
//            CertificateProfileDO certificateProfileDO = certificateProfileService.selectById(coursesDO.getProfileId());
//            if(certificateProfileDO != null){
//                String cerName;
//                if(certificateProfileDO.getName().length() > 4){
//                    cerName = certificateProfileDO.getName().substring(0, 4);
//                }else{
//                    cerName = certificateProfileDO.getName();
//                }
                OrganizationNewsDO organizationNewsDO = organizationNewsService.selectById(coursesDO.getOrgId());
                if (organizationNewsDO != null) {
                    //证书图片
                    String cerImgUrl = null;
                    String cerImgUrlNoSale = null;

                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    String dateNow = sdf.format(new Date());
                    //具体的年、月、日可利用substring截取
                    //dateNow.substring(开始下标，结束下标),下标原则：从0开始，包前不包后
                    String cerYear = dateNow.substring(0, 4);
                    String cerMath = dateNow.substring(5, 7);
                    String cerDay = dateNow.substring(8, 10);

                    String dateNow1 = sdf.format(coursesDO.getCreaterDate());
                    String traYear = dateNow1.substring(0, 4);
                    String traMath = dateNow1.substring(5, 7);
                    String traDay = dateNow1.substring(8, 10);
                    //获取当前年份后两位
                    String yearRe = traYear.substring(2,4);

                    Map mapss = new HashMap();
                    //获取背景图片
                    if (coursesDO.getType().equals(1) || coursesDO.getType().equals(3)) {
                        mapss.put("name", "师资培训证书背景图");
                        mapss.put("type", "tra_tea_synthesis");
                    } else if(coursesDO.getType().equals(2) || coursesDO.getType().equals(4)){
                        mapss.put("name", "考评员培训证书背景图");
                        mapss.put("type", "tra_exa_synthesis");
                    }
                    String traSynthesis = dictService.selDicBy(mapss);
                    if (StringUtils.isNotBlank(traSynthesis)) {
                        traSynthesis = ValuesUtil.localUrl + traSynthesis;
                    }

                    String electronicSeal = null;
                    String effectiveDate = null;
                    if (coursesDO.getType().equals(1) || coursesDO.getType().equals(3)) {
                        //获取电子公章
                        mapss.clear();
                        mapss.put("name", "金职电子公章");
                        mapss.put("type", "electronic_seal");
                        electronicSeal = dictService.selDicBy(mapss);
                        if (StringUtils.isNotBlank(electronicSeal)) {
                            electronicSeal = ValuesUtil.localUrl + electronicSeal;
                        }
                    } else if(coursesDO.getType().equals(2) || coursesDO.getType().equals(4)){
                        //获取证书有效时长
                        mapss.clear();
                        mapss.put("name", "培训证书有效时长");
                        mapss.put("type", "tra_cer_time");
                        String traCerTime = dictService.selDicBy(mapss);
                        if (StringUtils.isNotBlank(traCerTime)) {
                            //判断是否为数字
                            if (!IdCardUtil.isNumeric(traCerTime)) {
                                return false;
                            }
                        }else{
                            traCerTime = "3";
                        }
                        String string = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
                        LocalDate today = LocalDate.now();
                        LocalDate timeDay = today.plus(Integer.parseInt(traCerTime), ChronoUnit.YEARS);
                        effectiveDate = string + "至" + timeDay;
                    }

                    String cerNumbers = "";//证书编号
                    if (coursesDO.getType().equals(1)) {
                        cerNumbers = comNumber("JZ", "师资", organizationNewsDO.getProvince(), coursesDO.getName(), yearRe, traMath);
                    } else if (coursesDO.getType().equals(2)) {
                        cerNumbers = comNumber("JZ", "考评员", organizationNewsDO.getProvince(), coursesDO.getName(), yearRe, traMath);
                    } else if (coursesDO.getType().equals(3)) {
                        cerNumbers = comNumber("JZ", "高级师资", organizationNewsDO.getProvince(), coursesDO.getName(), yearRe, traMath);
                    } else if (coursesDO.getType().equals(4)) {
                        cerNumbers = comNumber("JZ", "高级考评员", organizationNewsDO.getProvince(), coursesDO.getName(), yearRe, traMath);
                    }

                    if (cerNumbers.contains("填写错误")) {
                        return false;
                    }
                    int cerEnd = 0;

                    //查询出该证书编号最大值
                    String cerNumber = trainingCertificatesService.selCerNumber(cerNumbers);
                    if (StringUtils.isNotBlank(cerNumber)) {
                        cerEnd = Integer.parseInt(cerNumber.substring(cerNumber.length() - 4));
                    }

                    cerNumbers = cerNumbers + WithZoreUtil.frontCompWithZore(cerEnd + 1, 4);//证书编号

                    if (coursesDO.getType().equals(1) || coursesDO.getType().equals(3)) {
                        //师资证书
                        //查询章节数
                        List<ChapterDO> chapterDOS = chapterService.findByKv("courses_id", coursesId);
                        try {
                            //参数说明：合成类型（0带公章，1不带公章），背景图，学员姓名，学员图像， 身份证号码，证书编码，考核期数，培训章节数（学时），培训年份，培训月份，培训日期，获证年份，获证年份，获证年份，电子公章
                            cerImgUrl = CerSynthesisUtil.overTrainingImage(0, traSynthesis, userName, url, userIdCard, cerNumbers,
                                    coursesDO.getName().substring(coursesDO.getName().length() - 4, coursesDO.getName().length() - 2), String.valueOf(chapterDOS.size()),
                                    traYear, traMath, traDay,cerYear,cerMath,cerDay, electronicSeal,workUnit,0);
                            cerImgUrlNoSale = CerSynthesisUtil.overTrainingImage(1, traSynthesis, userName, url, userIdCard, cerNumbers,
                                    coursesDO.getName().substring(coursesDO.getName().length() - 4, coursesDO.getName().length() - 2), String.valueOf(chapterDOS.size()),
                                    traYear, traMath, traDay,cerYear,cerMath,cerDay, electronicSeal,workUnit,0);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    } else if(coursesDO.getType().equals(2) || coursesDO.getType().equals(4)){
                        //考评员证书
                        try {
                            //参数说明：背景图，学员姓名，学员图像， 身份证号码，证书编码，证书名称，有效日期
                            cerImgUrl = CerSynthesisUtil.overTraExaImage(traSynthesis, userName, url, userIdCard, cerNumbers, effectiveDate,workUnit,0);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    if(!coursesDO.getType().equals(0)){
                        //这里新增培训证书信息
                        TrainingCertificatesDO trainingCertificatesDO = trainingCertificatesService.findOneByKv("user_id", userId, "courses_id", coursesId);
                        if (trainingCertificatesDO == null) {
                            TrainingCertificatesDO trainingCertificatesDO1 = new TrainingCertificatesDO();
                            trainingCertificatesDO1.setUserId(userId);
                            trainingCertificatesDO1.setCoursesId(coursesId);
                            trainingCertificatesDO1.setQueries(0);//查询次数
                            trainingCertificatesDO1.setGetTime(new Date());
                            trainingCertificatesDO1.setNumbers(cerNumbers);
                            if (!coursesDO.getType().equals(0)) {
                                //转换一下图片路径，将反斜杠替换掉
                                String urlss = cerImgUrl.replace(ValuesUtil.localUrl, ValuesUtil.returnUrl);
                                String imgUrl1 = urlss.replace("\\", "/");
                                trainingCertificatesDO1.setImgUrl(imgUrl1);
                                if (coursesDO.getType().equals(1) || coursesDO.getType().equals(3)) {
                                    String url1 = cerImgUrlNoSale.replace(ValuesUtil.localUrl, ValuesUtil.returnUrl);
                                    String imgUrl2 = url1.replace("\\", "/");
                                    trainingCertificatesDO1.setImgUrlNosale(imgUrl2);
                                }
                            }
                            trainingCertificatesDO1.setState(0);//状态，默认正常
                            boolean tras = trainingCertificatesService.insert(trainingCertificatesDO1);
                            if (tras) {
                                return true;
                            } else {
                                return false;
                            }
                        }
                    }
                }else{
                    return false;
                }
//            }else{
//                return false;
//            }
        } else {
            return false;
        }
        return true;
    }


    /**
     * api小程序端-获取答卷列表接口
     *
     * @Description: 获取当前用户的所有答卷信息列表；参数：验证token,课程id
     * @Param: [token，id]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-04-26
     */
    @GetMapping("/selTraAnswerList")
    @Log("api小程序端-获取答卷列表接口")
    @ApiOperation(value = "api小程序端-获取答卷列表接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> selTraAnswerList(@RequestHeader(value = TOKEN_TAG, required = false) String token, String id) {
        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }
        if (StringUtils.isBlank(id)) {
            return ApiResult.lack("");//缺少参数
        }
        List<Map> mapre = new ArrayList<>();
        List<TrainingPapersDO> trainingPapersDOS = trainingPapersService.findByKv("courses_id", id);
        if (trainingPapersDOS != null && trainingPapersDOS.size() > 0) {
            for (TrainingPapersDO trainingPapersDO : trainingPapersDOS) {
                Map map = new HashMap();
                map.put("tpaperId", trainingPapersDO.getId());
                map.put("tpaperName", trainingPapersDO.getName());
                map.put("type", trainingPapersDO.getType());
                TrainingAnswerSheetDO trainingAnswerSheetDO = trainingAnswerSheetService.findOneByKv("user_id", user.getId(), "tpapers_id", trainingPapersDO.getId());
                if (trainingAnswerSheetDO != null) {
                    map.put("id", trainingAnswerSheetDO.getId());

                    TrainingResultsDO trainingResultsDO = trainingResultsService.findOneByKv("tpapers_id", trainingAnswerSheetDO.getTpapersId(), "user_id", user.getId());
                    if (trainingResultsDO != null) {
                        map.put("score", trainingResultsDO.getTotalScore());//考试成绩
                    } else {
                        map.put("score", 0);//考试成绩
                    }
                    mapre.add(map);
                }
            }
        }

        return ApiResult.success(mapre);
    }


    /**
     * api小程序端-获取答卷详情接口
     *
     * @Description: 根据答卷id，获取答卷信息详情；参数：答卷id
     * @Param: [token, id]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-04-26
     */
    @GetMapping("/selTraAnswerDetails")
    @Log("api小程序端-获取答卷详情接口")
    @ApiOperation(value = "api小程序端-获取答卷详情接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> selTraAnswerDetails(@RequestHeader(value = TOKEN_TAG, required = false) String token, String id) {
        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }
        if (StringUtils.isBlank(id)) {
            return ApiResult.lack("");//缺少参数
        }

        TrainingAnswerSheetDO trainingAnswerSheetDO = trainingAnswerSheetService.selectById(Long.parseLong(id));
        if (trainingAnswerSheetDO != null) {
            trainingAnswerSheetDO.setUserName(user.getName());

            if (trainingAnswerSheetDO.getTpapersId() != null) {
                TrainingPapersDO trainingPapersDO = trainingPapersService.selectById(trainingAnswerSheetDO.getTpapersId());
                if (trainingPapersDO != null) {
                    trainingAnswerSheetDO.setTpapersName(trainingPapersDO.getName());
                    if (trainingPapersDO.getType().equals(0)) {
                        //只有为练习类型时，才能有答卷详情信息
                        List<Map> maps = new ArrayList<>();
                        Integer results = 0;
                        String[] ssr = trainingAnswerSheetDO.getAnswers().split("\\{\"id\":\"");
                        for (int i = 1; i < ssr.length; i++) {
                            Map map = new HashMap();
                            String[] ssc = ssr[i].split("\"}");
                            for (int j = 0; j < ssc.length; j++) {
                                String[] ssa = ssc[j].split("\",\"value\":\"");
                                if (ssa.length > 1) {
                                    TrainingQuestionsDO trainingQuestionsDO = trainingQuestionsService.selectById(ssa[0]);
                                    map.put("titleNumber", trainingQuestionsDO.getTitleNumber());//题号
                                    map.put("introduce", trainingQuestionsDO.getIntroduce());//题目内容
                                    map.put("titleOptions", trainingQuestionsDO.getOptions());//题目选项
                                    map.put("type", trainingQuestionsDO.getType());//题目类型（0单选，1多选，2判断）
                                    map.put("topicAnalysis", trainingQuestionsDO.getTopicAnalysis());//题目解析
                                    if (trainingQuestionsDO.getType() == 0 || trainingQuestionsDO.getType() == 2) {//单选题和判断题，答案唯一，可以不用拆解了
                                        if (trainingQuestionsDO.getRightKey().equals(ssa[1])) {
                                            map.put("answers", trainingQuestionsDO.getRightKey());//正确答案
                                            map.put("options", ssa[1]);//考生选项
                                            map.put("yesOrNo", "是");
                                            results = results + trainingQuestionsDO.getScore();
                                        } else {
                                            map.put("answers", trainingQuestionsDO.getRightKey());//正确答案
                                            map.put("options", ssa[1]);//考生选项
                                            map.put("yesOrNo", "否");
                                        }
                                    } else if (trainingQuestionsDO.getType() == 1) {//多选题因为答案有多个，需要循环判断一下是否包含该答案
                                        String[] ssb = ssa[1].split(";;");
                                        String answer = "";
                                        for (int n = 0; n < ssb.length; n++) {
                                            if (answer == "") {
                                                answer = ssb[n];
                                            } else {
                                                answer = answer + ";;" + ssb[n];
                                            }
                                        }

                                        if (trainingQuestionsDO.getRightKey().equals(answer)) {
                                            map.put("answers", trainingQuestionsDO.getRightKey());//正确答案
                                            map.put("options", answer);//考生选项
                                            map.put("yesOrNo", "是");
                                            results = results + trainingQuestionsDO.getScore();
                                        } else {
                                            map.put("answers", trainingQuestionsDO.getRightKey());//正确答案
                                            map.put("options", answer);//考生选项
                                            map.put("yesOrNo", "否");
                                        }
                                    }
                                    maps.add(map);
                                } else if (ssa.length == 1 && !ssa[0].equals(",") && !ssa[0].equals("]")) {
                                    TrainingQuestionsDO trainingQuestionsDO = trainingQuestionsService.selectById(ssa[0]);
                                    map.put("titleNumber", trainingQuestionsDO.getTitleNumber());//题号
                                    map.put("introduce", trainingQuestionsDO.getIntroduce());//题目内容
                                    map.put("titleOptions", trainingQuestionsDO.getOptions());//题目选项
                                    map.put("type", trainingQuestionsDO.getType());//题目类型（0单选，1多选，2判断）
                                    map.put("topicAnalysis", trainingQuestionsDO.getTopicAnalysis());//题目解析
                                    map.put("answers", trainingQuestionsDO.getRightKey());//正确答案
                                    map.put("options", "");//考生选项
                                    map.put("yesOrNo", "否");
                                    maps.add(map);
                                }
                            }
                        }
                        trainingAnswerSheetDO.setAnswerLists(maps);
                        trainingAnswerSheetDO.setScore(results);
                    } else {
                        return ApiResult.fail("信息错误，请重试或联系管理员");
                    }
                } else {
                    trainingAnswerSheetDO.setTpapersName("----");
                }
            }

            return ApiResult.success(trainingAnswerSheetDO);
        } else {
            return ApiResult.fail("答卷信息有误，请重试或联系管理员");
        }
    }

    @GetMapping("/stuRcdList")
    @Log("我的学习记录接口")
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> stuRcdList(@RequestHeader(value = TOKEN_TAG, required = false) String token, int current, int number) {
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }
        Page<LearnRecordDO> page = learnRecordService.stuRcdList(current, number, user.getId());
        List<LearnRecordDO> list = page.getRecords();
        for (LearnRecordDO learnRecord : list) {
            UserDO users = userService.selectById(user.getId());
            if (users.getName() != null) {
                learnRecord.setUserName(users.getName());
            }

            CoursesDO courses = coursesService.selectById(learnRecord.getCoursesId());
            if (courses != null && courses.getName() != null) {
                learnRecord.setCoursesName(courses.getName());
            }

            ChapterDO chapter = chapterService.selectById(learnRecord.getChapterId());
            if (chapter != null && chapter.getName() != null) {
                learnRecord.setChapterName(chapter.getName());
            }
        }
        page.setRecords(list);
        return ApiResult.success(page);
    }
}
